package com.rabbit.rabbitmqdemo.service;

import com.rabbit.rabbitmqdemo.entity.User;
import com.rabbit.rabbitmqdemo.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Component
@Transactional
public class UserService {

	final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	JdbcTemplate jdbcTemplate;
	@Autowired
	private UserRepository userRepository;

	RowMapper<User> userRowMapper = new BeanPropertyRowMapper<>(User.class);

	public User getUserById(long id) {
		return userRepository.getOne(id);
//		return jdbcTemplate.queryForObject("SELECT * FROM users WHERE id = ?", new Object[] { id }, userRowMapper);
	}

	public User getUserByEmail(String email) {
		return userRepository.getUserByEmail(email);
//		return jdbcTemplate.queryForObject("SELECT * FROM users WHERE email = ?", new Object[] { email },
//				userRowMapper);
	}

	public User signin(String email, String password) {
		logger.info("try login by {}...", email);
		User user = getUserByEmail(email);
		if (user.getPassword().equals(password)) {
			return user;
		}
		throw new RuntimeException("login failed.");
	}

	public User register(User user) {
		logger.info("try register by {}...", user.getEmail());

		User usaved = userRepository.save(user);
		return usaved;
//		KeyHolder holder = new GeneratedKeyHolder();
//		if (1 != jdbcTemplate.update((conn) -> {
//			PreparedStatement ps = conn.prepareStatement("INSERT INTO users(email,password,name,createdAt) VALUES(?,?,?,?)",
//					Statement.RETURN_GENERATED_KEYS);
//			ps.setObject(1, user.getEmail());
//			ps.setObject(2, user.getPassword());
//			ps.setObject(3, user.getName());
//			ps.setObject(4, user.getCreatedAt());
//			return ps;
//		}, holder)) {
//			throw new RuntimeException("Insert failed.");
//		}
//		user.setId(holder.getKey().longValue());
//		return user;
	}

	public void updateUser(User user) {
		User uupdated = userRepository.save(user);
		Optional<User> u = userRepository.findById(user.getId());
		if (!u.isPresent()){
			throw new RuntimeException("User not found by id");
		}
//		if (1 != jdbcTemplate.update("UPDATE users SET name = ? WHERE id=?", user.getName(), user.getId())) {
//
//		}
	}

	public List<User> getUsers() {
		return userRepository.findAll();
//		return jdbcTemplate.query("SELECT * FROM users", userRowMapper);
	}
}
